<template>
  <div class="searchSuggest">
    <van-cell icon="search" 
    v-for="(str, index) in suggestions"
     :key="index"
     @click="$emit('search',str.name)"
    >
      <div slot="title" v-html="highlight(str.name)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuccest } from "@/api/search";
// 导入函数防抖插件
import { debounce } from "lodash";

export default {
  name: "searchSuggest",
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [], //联想列表数据
    };
  },
  watch: {
    //   这才是完整写法
    searchText: {
      handler: debounce(async function () {
        const { data } = await getSearchSuccest({
          keywords: this.searchText,
        });
        this.suggestions = data.result.songs;
      }, 100),
      immediate: true, //该回调将会在侦听开始之后被立即调用
    },
  },
  methods: {
    highlight(str) {
      const height = `<span style="color:red">${this.searchText} </span>`;
      //   正则表达式 /中间的内容/ 都会被当做正则匹配模式字符来对待
      //RegExp是正则表达式的构造函数
      return str.replace(new RegExp(this.searchText, "gi"), height);
    },
  },
};
</script>

<style lang="less" scoped>
</style>